//load
function resolveReferences(xopusDoc, startNode)
{
  var refs = startNode.selectNodes(".//*[@conref]");
  for (var i=refs.getLength(); i--;)
  {
    var node = refs.item(i);
    resolveReference(xopusDoc, node);
    node.makeValid();
  }
}

function resolveReference(xopusDoc, node)
{
  //where is referring
  var conref = node.getAttribute("conref");

  //what file
  var file = conref.substring(0, conref.indexOf("#"));

  //it works by id)
  var id = conref.substring(conref.indexOf("#")+1);

  //load the refferenced document
  var refDoc = HTTPTools.getXML(xmlpath+file);

  //get the right element
  var refNode = refDoc.selectSingleNode("//*[@id = '"+id+"']");

  //parse element
  complete(xopusDoc, node, refNode);

  // resolve references inside newly added content
  resolveReferences(xopusDoc, node);
}

function complete(xopusDoc, docNode, refNode)
{
  //copy every childNode of the refNode to the docNode in the xopusDoc
  for (var i=0; i<refNode.childNodes.length; i++)
  {
    var refChild = refNode.childNodes[i];
    switch (refChild.nodeType)
    {
      case 1:
        var newNode;
        if (refChild.nodeName == "title" && docNode.getLocalName() == "topic")
        {
          newNode = docNode.getFirstChild();
          newNode.setTextContent("");
        }
        else
        {
          newNode = xopusDoc.createElement(refChild.nodeName);
          docNode.appendChild(newNode)
        }

        for (var j=0; j<refChild.attributes.length; j++)
          newNode.setAttribute(refChild.attributes[j].name, refChild.attributes[j].value);

        //parse childNodes
        complete(xopusDoc, newNode, refChild);
        break;
      case 3:
        docNode.appendChild(xopusDoc.createTextNode(refChild.data));
        break;
    }
  }
}

function checkReference(evt)
{
  var node = evt.attrNode?evt.attrNode:evt.target;

  var xopusDoc = node.getOwnerDocument();
  if (node.getNodeName() == "conref")
  {
    var element = node.getOwnerElement();
    if (evt.newValue != evt.oldValue && evt.newValue != "" || node.getNodeValue() != "")
    {
      cleanContents(element);
      try
      {
        resolveReference(xopusDoc, element);
        element.makeValid();
      }
      catch(e)
      {
      }
    }
  }
}


function cleanContents(element)
{
  if (element)
  {
    var childNodes = element.selectNodes("node()");
    childNodes.removeAll();

    if (element.getLocalName() == "topic")
      element.appendChild(element.getOwnerDocument().createElement("title"));
  }
}
